package com.steve.summary.seata.service.impl;

import com.steve.summary.seata.entity.Storage;
import com.steve.summary.seata.mapper.StorageMapper;
import com.steve.summary.seata.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: STEVE
 * @Description: 库存服务实现
 * @since: 2025-07-09
 */
@Service
@Slf4j
public class StorageServiceImpl implements StorageService {

    @Autowired
    private StorageMapper storageMapper;

    /**
     * 扣减库存
     *
     * @param productId 商品ID
     * @param count     扣减数量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void decrease(String productId, Integer count) {
        log.info("-------> 开始扣减库存");

        // 检查库存
        Storage storage = storageMapper.selectByProductId(productId);
        if (storage == null) {
            throw new RuntimeException("商品不存在");
        }
        if (storage.getResidue() < count) {
            throw new RuntimeException("库存不足");
        }

        // 扣减库存
        storageMapper.deductStock(productId, count);

        log.info("-------> 扣减库存完成");
    }

    /**
     * 查询商品库存
     *
     * @param productId 商品ID
     * @return 库存信息
     */
    @Override
    public Storage getByProductId(String productId) {
        return storageMapper.selectByProductId(productId);
    }

    /**
     * 恢复库存
     *
     * @param productId 商品ID
     * @param count     恢复数量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void increase(String productId, Integer count) {
        log.info("-------> 开始恢复库存");
        Storage storage = storageMapper.selectByProductId(productId);
        if (storage != null) {
            storageMapper.restoreStock(productId, count);
        }
        log.info("-------> 恢复库存完");
    }

}
